<template>
  <div class="labelManage" @click.self="unClick">
    <div class="tree-search-bar">
      <button class="add-btn" @click="typeOperate('add')">增加</button>
      <el-input
        v-model="filterText"
        style="width:200px"
        placeholder="输入关键字进行过滤"
        clearable
      />
    </div>
    <el-tree
      ref="tree"
      highlight-current
      :data="treeData"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false"
      :props="{
        label: 'text',
        children: 'nodes',
      }"
      :filter-node-method="filterNode"
    >
      <span slot-scope="{ node, data }" class="custom-tree-node">
        <span>
          <svg-icon :icon-class="data.iType==0?'icon-wenjianyi':'icon-wenbenmoban'" />
          {{ data.text }}
        </span>
        <span>
          <!--  v-if="data.iType==1" -->
          <template v-if="data.text=='学习路径'" />
          <template v-else>
            <template v-if="data.iType==1">
              <el-button v-if="showTop(data)" plain size="mini" @click="typeOperate('move', node, data, 1)">上移</el-button>
              <el-button v-if="showBottom(data)" plain size="mini" @click="typeOperate('move', node, data, 2)">下移</el-button>
              <el-button plain size="mini" @click="typeOperate('order', node, data)">学习路线排序</el-button>
            </template>
            <el-button plain size="mini" @click="typeOperate('edit', node, data)">修改</el-button>
            <el-button plain size="mini" @click="typeOperate('del', node, data)">删除</el-button>
          </template>
        </span>
      </span>
    </el-tree>
    <!-- 新增 -->
    <input-dialog v-if="inputDialogParams.visible" ref="input-dialog" :params="inputDialogParams" />
  </div>
</template>

<script>
import { getLearnGroupList, addLearnGroup, setLearnGroup, moveLearnGroup, delLearnGroup, getLearnGroup } from '@/api/learnCenter'
import { arrayToTree, treeFind } from '@/utils'
import InputDialog from '@/components/Dialog/InputDialog'
export default {
  name: 'TypeManage',
  components: { InputDialog },
  data() {
    return {
      treeData: [],
      inputDialogParams: {
        visible: false
      },
      filterText: ''
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    // 获取分类
    this.getTypeList()
  },
  methods: {
    // 获取类型列表
    getTypeList() {
      const vPar = new this.ParamArr()
      getLearnGroupList(vPar).then(vPar => {
        const nodes = []
        const table = new this.SQLTable(vPar.getTable('k_learn_group'))
        table.first()
        while (!table.eof()) {
          const node = {}
          node['id'] = table.getValueByName('ID')
          node['pid'] = table.getValueByName('PID')
          node['text'] = table.getValueByName('Name')
          node['remark'] = table.getValueByName('Remark')
          node['iType'] = table.getValueByName('iType')
          if (node['iType'] === '0') {
            node['icon'] = 'icon-wenjianyi'
          } else {
            node['icon'] = 'icon-wenbenmoban'
          }
          nodes.push(node)
          table.next()
        }
        this.treeData = arrayToTree(nodes, { children: 'nodes' })

        // 学习中心主动新建一个学习路径文件夹
        this.addStyleLineFile()
      })
    },
    // 学习中心主动新建一个学习路径文件夹
    addStyleLineFile() {
      const addStyleGroup = () => {
        // 添加一个学习路径文件夹
        const vPar = new this.ParamArr()
        vPar.setStr('PID', '')
        vPar.setStr('Name', '学习路径')
        vPar.setStr('Remark', '')
        vPar.setInt('iType', 0) // 1：分类 0：分组
        addLearnGroup(vPar).then(vPar => {
          const p_data = {
            id: vPar.getStr('ID'),
            pid: vPar.getStr('PID'),
            text: vPar.getStr('Name'),
            remark: vPar.getStr('Remark'),
            iType: 0,
            icon: 'icon-wenjianyi'
          }
          this.treeData.push(p_data)
        })
      }
      if (!this.treeData.length) {
        addStyleGroup()
      } else {
        // 遍历没有学习路径文件夹就新建一个
        let hasStulyGroup = false
        this.treeData.forEach(item => {
          if (item.text === '学习路径') {
            hasStulyGroup = true
          }
        })
        if (!hasStulyGroup) {
          addStyleGroup()
        }
      }
    },
    // 分类操作
    typeOperate(type, node, item, attachmode) {
      let iType = 0// 1：分类 0：分组
      switch (type) {
        case 'add':
          {
            const node = this.$refs.tree.getCurrentNode()
            this.inputDialogParams.title = '新增分类'
            this.inputDialogParams.formList = [
              { label: '分类名称', value: '', name: 'name' },
              { label: '分类描述', value: '', name: 'remark' }
            ]
            if (node) {
              if (node.iType == '1') return this.$message.warning('请选择分组添加分类')
              else {
                iType = 1
              }
            } else {
              return this.$message.warning('请选择分组添加分类')
              // iType = 0
              // this.inputDialogParams.title = '新增分组'
              // this.inputDialogParams.formList = [
              //   { label: '分组名称', value: '', name: 'name' }
              // ]
            }
            this.inputDialogParams.visible = true
            // 选中
            this.$nextTick(() => {
              this.$refs['input-dialog'].$refs['name0'][0].focus()
            })
            this.inputDialogParams.confirm = (form) => {
              if (!form.name) return this.$message.warning('请输入名称')
              if (!form.remark && iType == 1) return this.$message.warning('请输入描述')
              const vPar = new this.ParamArr()
              vPar.setStr('PID', '')
              node && vPar.setStr('PID', node.id)
              vPar.setStr('Name', form.name)
              vPar.setStr('Remark', form.remark)
              vPar.setInt('iType', parseInt(iType)) // 1：分类 0：分组
              addLearnGroup(vPar).then(vPar => {
                this.inputDialogParams.visible = false
                // 回显数据
                const p_data = {
                  id: vPar.getStr('ID'),
                  pid: vPar.getStr('PID'),
                  text: vPar.getStr('Name'),
                  remark: vPar.getStr('Remark'),
                  iType: parseInt(iType),
                  icon: vPar.getInt('iType') === 1 ? 'icon-wenbenmoban' : 'icon-wenjianyi'
                }
                if (p_data.pid) {
                  this.$refs.tree.append(p_data, node.id)
                } else {
                  const len = this.treeData.length
                  if (len) {
                    const b_data = this.treeData[len - 1]
                    this.$refs.tree.insertAfter(p_data, b_data)
                  } else {
                    this.treeData.push(p_data)
                  }
                }
              })
            }
          }
          break
        case 'order': // 课程排序
          this.$openUrl('CourseOrder', '', { id: item.id }, { id: item.id })
          break
        case 'edit':
          if (item.iType == '1') {
            this.inputDialogParams.title = '修改分类'
            this.inputDialogParams.formList = [
              { label: '分类名称', value: item.text, name: 'name' },
              { label: '分类描述', value: item.remark, name: 'remark' }
            ]
          } else {
            this.inputDialogParams.title = '修改分组'
            this.inputDialogParams.formList = [
              { label: '分组名称', value: item.text, name: 'name' }
            ]
          }

          this.inputDialogParams.visible = true
          // 选中
          this.$nextTick(() => {
            this.$refs['input-dialog'].$refs['name0'][0].focus()
          })
          this.inputDialogParams.confirm = (form) => {
            if (!form.name) return this.$message.warning('请输入名称')
            if (!form.remark && item.iType == 1) return this.$message.warning('请输入分类描述')
            const vPar = new this.ParamArr()
            vPar.setStr('ID', item.id)
            vPar.setStr('Name', form.name)
            vPar.setStr('Remark', form.remark)
            setLearnGroup(vPar).then(vPar => {
              this.inputDialogParams.visible = false
              // 回显数据
              const fitem = treeFind(vPar.getStr('ID'), this.treeData, { children: 'nodes' })
              if (fitem) {
                fitem.text = vPar.getStr('Name')
                fitem.remark = vPar.getStr('Remark')
              }
            })
          }
          break
        case 'move':
        {
          if (node.parent.data) {
            const pNode = node.parent.data
            const nodes = pNode.nodes
            let cNode = ''
            let index = -1
            if (nodes) {
              nodes.forEach((it, idx) => {
                if (it.id === item.id) {
                  index = idx
                }
              })
            }
            if (index != -1) {
              cNode = attachmode == 1 ? nodes[index - 1] : nodes[index + 1]
              const vPar = new this.ParamArr()
              vPar.setInt('Attachmode', attachmode)
              vPar.setStr('SrcID', item.id)
              vPar.setStr('DestID', cNode.id)
              moveLearnGroup(vPar).then(vPar => {
                this.getTypeList()
              })
            }
          }
          break
        }
        case 'del':
          this.$comfirmDialog({
            message: `是否将“${item.text}”删除?`,
            confirm: () => {
              const vPar = new this.ParamArr()
              vPar.setStr('ID', item.id)
              delLearnGroup(vPar).then(vPar => {
                this.$refs.tree.remove(vPar.getStr('ID'))
              })
            }
          })
          break
      }
    },
    // 点击外部取消树选中
    unClick() {
      this.$refs.tree.setCurrentKey(null)
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.text.indexOf(value) !== -1
    },
    // 显示上移
    showTop(data) {
      const fitem = treeFind(data.pid, this.treeData, { children: 'nodes' })
      let index = -1
      if (fitem && fitem.nodes) {
        const nodes = fitem.nodes
        nodes.forEach((item, idx) => {
          if (item.id === data.id) {
            index = idx
          }
        })
        if (index === 0) {
          return false
        }
      }
      return true
    },
    // 显示下移
    showBottom(data) {
      const fitem = treeFind(data.pid, this.treeData, { children: 'nodes' })
      let index = -1
      if (fitem && fitem.nodes) {
        const nodes = fitem.nodes
        nodes.forEach((item, idx) => {
          if (item.id === data.id) {
            index = idx
          }
        })
        if (index === (nodes.length - 1)) {
          return false
        }
      }
      return true
    }
  }
}
</script>

<style scoped lang="scss">
.labelManage {
  width: 100%;
  padding: 10px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.tree-search-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 5px;
}
.add-btn {
  width: 96px;
  height: 30px;
  background-color: $primaryColor;
  font-size: 14px;
  color: #ffffff;
  outline: none;
  border: none;
  cursor: pointer;
}
::v-deep .el-tree .el-tree-node.is-current > .el-tree-node__content {
  background: #c1e8f2;
}
</style>
